var LAST_YEAR = (new Date()).getFullYear() - 1;
var http = new ActiveXObject("Msxml2.XMLHTTP");
var positions = {};

var pause = true;
var proceed = true;
var iMlbPlayer = 0;
for ( iChar = 'A'.charCodeAt(0); iChar <= 'Z'.charCodeAt(0); iChar++ )
{
	var initial = String.fromCharCode( iChar );
	//if ( initial != 'B' )
	//	continue;

	var url = "http://sports.yahoo.com/mlb/players?type=lastname&query=" + initial;

	getHttpRequest( http, url );
	if ( http.status != 200 )
	{
		WScript.StdErr.WriteLine( '  Failed request: ' + http.status + ' ' + http.statusText );
		break;
	}

	var html = http.responseText.replace( /(\r\n|\n)+/g, '' );
	html = html.replace( /^.*?(<tr class="ysprow)/i, '$1' );

	if ( /No players found/i.test( html ) )
		continue;

	var players = html.split( /<tr class="ysprow/i );
	for ( var iTeamPlayer = 0; iTeamPlayer < players.length; iTeamPlayer++ )
	{
		var matches = players[ iTeamPlayer ].match( /<a\s+.*?href="([^"]+)".*?>([^<]+)<\/a>.*?<a\s+.*?href="[^"]+teams[^"]+".*?>([^<]+)<\/a>/ );
		if ( matches )
		{
			var url = 'http://sports.yahoo.com' + matches[ 1 ] + "/career";
			var player = stripAccent( matches[ 2 ] );
			var team = matches[ 3 ];
			iMlbPlayer += 1;
			WScript.Echo( iMlbPlayer + '.' + ( iTeamPlayer + 1 ) + ' ' + player );
			WScript.StdErr.WriteLine( iMlbPlayer + '.' + ( iTeamPlayer + 1 ) + ' ' + player + ' (' + url + ')' );

			getHttpRequest( http, url );
			if ( http.status != 200 )
			{
				WScript.StdErr.WriteLine( '  Failed request: ' + http.status + ' ' + http.statusText );
				break;
			}

			var html = http.responseText.replace( /(\r\n|\n)+/g, '' );
			html = html.replace( /^.*?<td\s+.*?class="ysptblhdr">[^<]*Fielding<\/td>\s*<\/tr>/i, '' );
			var header = html.replace( /(^.*?<\/tr>).*/i, '$1' ).replace( /<\/?tr[^>]*>/ig, '' );
			var captions = header.split( /(<\/?td[^>]*>\s*)+|(&nbsp;)+/i );
			captions.splice( 0, 1 );

			WScript.Echo( '\t' + captions.join( ', ' ) );

			html = html.replace( /^\s*<tr[^>]+>.*?<\/tr>(.*?)<\/table>.*$/i, '$1' );
			var dataRows = html.split( /(<\/?tr[^>]*>\s*)+/i );
			var playerPositions = {};
			for ( var iRow = 0; iRow < dataRows.length; iRow++ )
			{
				var values = dataRows[ iRow ].split( /(<\/?td[^>]*>\s*)+|(&nbsp;)+/i );
				if ( parseInt( values[ 0 ], 10 ) == LAST_YEAR )
				{
					WScript.Echo( '\t' + values.join( ', ' ) );
					var team = values[ 1 ];
					var pos = values[ 2 ];
					var games = parseInt( values[ 3 ], 10 );
					var starts = parseInt( values[ 4 ], 10 );
					if ( !playerPositions.hasOwnProperty( pos ) )
						playerPositions[ pos ] = { games:0, starts:0, teams:new Array() };
					playerPositions[ pos ].games += games;
					playerPositions[ pos ].starts += starts;
					playerPositions[ pos ].teams.push( team );
				}
			}
			for ( var pos in playerPositions )
			{
				WScript.Echo( '\t' + pos + ' ' + playerPositions[ pos ].games + '/' + playerPositions[ pos ].starts + ', ' + playerPositions[ pos ].teams.join( '/' ) );
				if ( !positions.hasOwnProperty( pos ) )
					positions[ pos ] = new Array();
				positions[ pos ].push( { player:player, games:playerPositions[ pos ].games, starts:playerPositions[ pos ].starts, teams:playerPositions[ pos ].teams } );
			}
		}
		if ( pause && iTeamPlayer > 0 && ( iTeamPlayer + 1 ) % 5 == 0 )
		{
			WScript.StdErr.Write( 'Continue... [Q)uit, C)ontinue w/o pausing]' );
			switch ( WScript.StdIn.ReadLine().toUpperCase() )
			{
			case 'Q':
				proceed = false;
				break;
			case 'C':
				pause = false;
				break;
			}
		}
		if ( !proceed )
			break;
	}
	if ( !proceed )
		break;
}

for ( var pos in positions )
{
	positions[ pos ].sort( byGames );
	for ( var iPlayer = 0; iPlayer < positions[ pos ].length; iPlayer++ )
	{
		WScript.Echo( positions[ pos ][ iPlayer ].player +
			' (' + positions[ pos ][ iPlayer ].teams.join( '/' ) +
			'), ' + pos +
			', ' + positions[ pos ][ iPlayer ].games +
			', ' + positions[ pos ][ iPlayer ].starts );
	}
}

function byGames( p1, p2 )
{
	if ( p1.games > p2.games )
		return -1;
	if ( p1.games < p2.games )
		return 1;
	return 0;
}

function stripAccent(str)
{
    var s=str;

    var rExps=[
    /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
    /[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
    /[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
    /[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
    /[\xD9-\xDB]/g, /[\xF9-\xFB]/g,
    /[\xD1]/g, /[\xF1]/g ];

    var repChar=['A','a','E','e','I','i','O','o','U','u','N','n'];

    for(var i=0; i<rExps.length; i++)
        s=s.replace(rExps[i],repChar[i]);

    return s;
}

function getHttpRequest( http, url )
{
	var attempts = 6;
	do
	{
		WScript.StdErr.WriteLine( 'Retrieving ' + url );
		http.open( "GET", url, false );
		http.send( null );
		if ( http.status != 200 )
		{
			var ms = 1000 * 60 * 60 * 4;
			WScript.StdErr.WriteLine( '  Error: ' + http.status + ' ' + http.statusText + ' (' + new Date() + ')' );
			WScript.StdErr.WriteLine( '  Waiting ' + ( ms / 1000 / 60 / 60 ) + ' hours to retry...' );
			WScript.Sleep( ms );
		}
	}
	while ( http.status != 200 && --attempts > 0 );
}